package cn.sundat.dao;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import cn.sundat.model.PageBean;

public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> {
	
	private Class clazz;
	/*
	 * 在父类的无参构造方法中获取子类泛型类
	 */
	public BaseDaoImpl() {
		// 表示的子类Class对象
		Class c = this.getClass();
		// 获取到的是c类的超类
		Type type = c.getGenericSuperclass();
		// 目的：把type接口转换成子接口
		if(type instanceof ParameterizedType){
			ParameterizedType ptype = (ParameterizedType) type;
			// 获取泛型类
			Type[] types = ptype.getActualTypeArguments();
			this.clazz = (Class) types[0];
		}
	}

	public void save(T t) {
		this.getHibernateTemplate().save(t);
	}

	public void delete(T t) {
		this.getHibernateTemplate().delete(t);
	}

	public void update(T t) {
		this.getHibernateTemplate().update(t);
	}

	public T getById(Long id) {
	 	return (T) this.getHibernateTemplate().get(clazz, id);
	}

	public List<T> findAll() {
		return (List<T>) this.getHibernateTemplate().find("from "+clazz.getSimpleName());
	}

	public PageBean<T> findByPage(Integer currPage, Integer pageSize, DetachedCriteria criteria) {
		PageBean<T> pb = new PageBean<T>();
		pb.setCurrPage(currPage);
		pb.setPageSize(pageSize);
		/**
		 * 聚合函数查询条数
		 */
		criteria.setProjection(Projections.rowCount());
		List<Number> list = (List<Number>) this.getHibernateTemplate().findByCriteria(criteria);
		if(list!=null && list.size()>0) {
			pb.setTotalCount(list.get(0).intValue());
		}
		//置空聚合函数查询
		criteria.setProjection(null);
		List<T> beanList = (List<T>) this.getHibernateTemplate().findByCriteria(criteria, (currPage-1)*pageSize, pageSize);
		pb.setBeanlist(beanList);
		return pb;
	}
	
}
